package com.shareloke.server.handler

import com.shareloke.server.netty.constant.NettyConst.ROOT_PATH
import com.shareloke.server.netty.constant.NettyConst.WEBSOCKET_PATH
import com.shareloke.server.netty.model.SocketMessage
import com.shareloke.server.tools.MyChannelManager
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.handler.codec.http.FullHttpRequest

/**
 *
 *  描述：自定义连接处理器。用来提取绑定用户id和channel。
 *
 * @author wlp
 * @version 1.0.0
 * @date 2021/7/13 上午 11:12
 */
class MyWebsocketConnectHandler : ChannelInboundHandlerAdapter() {

    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        if (msg is FullHttpRequest) {
            val uri = msg.uri()
            if (null == msg.headers()["Origin"]) {
                ctx.close()
            } else {
                if (null != uri && uri.contains(WEBSOCKET_PATH)) {
                    val split = uri.split(ROOT_PATH).toTypedArray()
                    if (split.isNotEmpty()) {
                        val userId = split[2]
                        val info = "$userId 上线 大家欢迎 目前在线 ${MyChannelManager.size() + 1}人"
                        MyChannelManager.sendAll(SocketMessage(info, "我是标题", "0"))
                        MyChannelManager.addChannel(userId, ctx.channel())
                        println(info)
                    }
                    msg.uri = WEBSOCKET_PATH
                }
            }
        }
        super.channelRead(ctx, msg)
    }

    @Throws(Exception::class)
    override fun channelInactive(ctx: ChannelHandlerContext) {
        val username = MyChannelManager.getUserId(ctx.channel())
        MyChannelManager.removeChannel(ctx.channel().id())
        val info = "$username 下线 目前在线 ${MyChannelManager.size()}人"
        println(info)
        MyChannelManager.sendAll(SocketMessage(info, "我是标题", "0"))
    }
}